const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

class MyPlugin {
  apply(compiler) {
    console.log('MyPlugin 启动')
    compiler.hooks.emit.tap('MyPlugin', (compilation) => {
      for(const name in compilation.assets) {
        const content = compilation.assets[name].source()
        console.log(typeof content)
        // console.log('content---', content)
        if(typeof content === 'Object') {
          const withoutComments = JSON.stringify(content.replace(/\/\*\*+\*\//g, ''))
          compilation.assets[name] = {
            source: () => withoutComments,
            size: () => withoutComments.length
          }
        }
        
      }
    })
  }
}

module.exports = {
  mode: 'none',
  entry: './src/main.js',
  output: {
    // filename: 'bundle.js',
    path: path.join(__dirname, 'dist')
  },
  // source-map，可以在调试时查看源码
  // devtool: 'source-map',
  
  // devServer: {
  //   proxy: {
  //     '/api': {
  //       target: 'https://api.github.com',
  //       pathRewrite: { '^/api': '' },
  //       changeOrigin: true,
  //     }
  //   }
  // },
  module: {
    rules: [
      {
        test: /.md$/,
        use: [
          // 执行顺序从后向前，把先执行的放到数组后面
          'html-loader',
          './markdown-loader.js'
        ]
      },
      {
        test: /.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    // 打包前清空dist目录
    new CleanWebpackPlugin(),
    // 将index.html生成到dist目录
    new HtmlWebpackPlugin({
      // html title
      title: 'Webpack Plugin Sample',
      // meta 设置页面中的源数据标签
      meta: {
        viewport: 'width=device, initial-scale=1'
      },
      template: './public/index.html'
    }),
    // 用于生成 about.html
    // new HtmlWebpackPlugin({
    //   filename: 'about.html',
    //   // template: './src/index.html',
    //   // chunks: ['about']
    // }),
    // new CopyWebpackPlugin({
    //   patterns: [
    //     {
    //       from: 'public',
    //       to: ''
    //     }
    //   ]
    // }),
    // new MyPlugin()
  ]
}